package org.ciallo.simplemusicplayer.fragment;

import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.widget.Toast;
import androidx.annotation.Nullable;
import androidx.lifecycle.ViewModelProvider;
import androidx.preference.ListPreference;
import androidx.preference.Preference;
import androidx.preference.PreferenceFragmentCompat;
import org.ciallo.simplemusicplayer.R;
import org.ciallo.simplemusicplayer.activity.AboutActivity;
import org.ciallo.simplemusicplayer.util.ThemeUtil;
import org.ciallo.simplemusicplayer.viewmodel.LocalMusicViewModel;

/**
 * @author Jukomu
 * @Description:
 * @Package: org.ciallo.simplemusicplayer.fragment
 * @Project: SimpleMusicPlayer
 * @name: SettingsFragment
 * @Date: 2025/6/2-00:32
 * @Filename: SettingsFragment
 */
public class SettingsFragment extends PreferenceFragmentCompat implements SharedPreferences.OnSharedPreferenceChangeListener {
    @Override
    public void onCreatePreferences(Bundle savedInstanceState, @Nullable String rootKey) {
        setPreferencesFromResource(R.xml.root_preferences, rootKey);

        // 为 "立即扫描" 设置点击监听
        Preference scanNowPref = findPreference("pref_scan_now");
        if (scanNowPref != null) {
            scanNowPref.setOnPreferenceClickListener(preference -> {
                if (getActivity() != null) {
                    // 通过 ViewModel 触发扫描，因为 Repository 和扫描逻辑已在那里
                    LocalMusicViewModel viewModel = new ViewModelProvider(requireActivity()).get(LocalMusicViewModel.class);
                    viewModel.startMediaStoreScan();
                    Toast.makeText(getContext(), "媒体库扫描已开始...", Toast.LENGTH_SHORT).show();
                }
                return true;
            });
        }

        // 为 "关于" 设置点击监听
        Preference aboutPref = findPreference("pref_about");
        if (aboutPref != null) {
            aboutPref.setOnPreferenceClickListener(preference -> {
                if (getActivity() != null) {
                    startActivity(new Intent(getActivity(), AboutActivity.class));
                }
                return true;
            });
        }

        // 你可能也需要为主题 ListPreference 设置一个初始的 summary
        ListPreference themePref = findPreference(ThemeUtil.PREF_THEME_KEY); // 使用常量
        if (themePref != null) {
            themePref.setSummary(themePref.getEntry()); // 将当前选中的项的文本设置为摘要
        }
    }

    @Override
    public void onSharedPreferenceChanged(SharedPreferences sharedPreferences, String key) {
        if (ThemeUtil.PREF_THEME_KEY.equals(key)) {
            // 当主题设置改变时
            Preference preference = findPreference(key);
            if (preference instanceof ListPreference) {
                // 更新摘要以显示新的选择
                ((ListPreference) preference).setSummary(((ListPreference) preference).getEntry());
            }

            // 从 SharedPreferences 中以字符串形式获取新的模式值
            String themeValue = sharedPreferences.getString(key, String.valueOf(androidx.appcompat.app.AppCompatDelegate.MODE_NIGHT_FOLLOW_SYSTEM));
            try {
                int mode = Integer.parseInt(themeValue);
                // 直接调用 ThemeUtil 来应用和保存（虽然 SharedPreferences 已自动保存，但 applyAndSaveNightMode 内部也应用了主题）
                ThemeUtil.applyAndSaveNightMode(requireContext(), mode);
            } catch (NumberFormatException e) {
                // Handle error
            }
        }
        // ... 处理其他设置项的改变
    }

    // 注册和注销 SharedPreferences 监听器
    @Override
    public void onResume() {
        super.onResume();
        getPreferenceManager().getSharedPreferences().registerOnSharedPreferenceChangeListener(this);
    }

    @Override
    public void onPause() {
        super.onPause();
        getPreferenceManager().getSharedPreferences().unregisterOnSharedPreferenceChangeListener(this);
    }
}
